class Uva
  def Uva.load_problems
    return 
    3.upto 27 do |page|
      if page == 4
         
      else
        url = URI.parse('http://icpcres.ecs.baylor.edu/onlinejudge/index.php')
        res = Net::HTTP.start(url.host, url.port) {|http|
          http.get('/onlinejudge/index.php?option=com_onlinejudge&Itemid=8&category=' + page.to_s)
        }
        body = res.body
        problem_table_selector = /(\<tr class=\"sectiontableheader\"\>.*?)<\/table\>/m
        body =~ problem_table_selector
        problem_table = "<table>" + $1 + "</table>"
        doc = REXML::Document.new(problem_table)
        number_getter = /problem=(\d*)/
        uva_source = Source.find_by_name("Uva")
        #puts "Stigna do stranica: " + page.to_s
        (2..(doc[0].size() - 1)).step(2) do |problem|
          #puts "Processing problem: " + problem.to_s
          description_id, name = doc[0][problem][3][0][0].value.split("&nbsp;-&nbsp;")
          submissions = doc[0][problem][5][0]
          submit_succ = doc[0][problem][7][1][3][0]
          authors = doc[0][problem][9][0]
          auth_succ = doc[0][problem][11][1][3][0]
          doc[0][2][3][0].attributes["href"] =~ number_getter
          submit_id = $1
          #puts "Predi construct id"
          problem_num = construct_real_id(description_id, submit_id)
          #puts "Realid: " + problem_num
         # puts "sled construct id"
          p = Problem.find(:first, 
            :conditions => {:real_identifier => problem_num, :source_id => uva_source.id})
          if p.nil?
            p = Problem.new
            p.name = name
            p.real_identifier = problem_num
            p.source = uva_source
          end
          #puts "Predi calculate diff"
          p.difficulty = calculate_difficulty(submissions, submit_succ, authors, auth_succ)
          #puts "sled calculate diff"
          p.save
        end
        #puts "Obrabotihme stranicata"
      end
    end
  end
    
  #partially working script
  def Uva.get_description(real_id)
    description_url = construct_description_url(real_id)
    url = URI.parse('http://icpcres.ecs.baylor.edu' + description_url)
    res = Net::HTTP.start(url.host, url.port) {|http|
      http.get(description_url)
    }
    problem_html_statement = res.body
    problem_html_statement
  end
   
  #not working script
  @Programming_languages = {:C => 1, :CPP => 2, :Paskal => 3, :CSharp => 4, :Java => 5}
  def Uva.submit_problem(source, problem, language, user)
    judge_id = SourceUser.find(:first, :conditions => 
        {:user_id => user.id, :source_id => Source.find_by_name("Timus").id}).username
        
    #submitting the problem
    hash = {"Action" => "submit", "Source" => source, 
      "Language" => @Programming_languages[language], 
      "JudgeID" => judge_id,
      "ProblemNum" => problem.real_identifier}
    Net::HTTP.post_form(URI.parse('http://acm.timus.ru/submit.aspx'), hash)
      
    #getting the id of the submit
    timus_status_url = URI.parse('http://acm.timus.ru/status.aspx')
    user_most_recent_status_page = '/status.aspx?count=10&id=' + judge_id[0, judge_id.length() - 2]
    status_extractor =/(\<TABLE class=\"status\".*?\<\/TABLE\>)/
    res = Net::HTTP.start(timus_status_url.host, timus_status_url.port) {|http|
      http.get(user_most_recent_status_page)
    }
      
    body = res.body
    body =~ status_extractor
    status_string = $1
    status_string.gsub!("<BR>"," ")

    status_xml = REXML::Document.new(status_string)
    status_xml.elements[1][1][0][0].value
  end
       
  #mock method
  def Uva.confirm_user(user, password)
    return true
  end
  
  def get
    uva_source = Source.find_by_name("Uva")
    temp_list = Run.find(:all, :conditions => {:status => nil})
    probs = temp_list.select{|run| run.problem.source == uva_source}
    res = retrieve_status(probs)
    #puts "Nqma da ima obnovqvane" if res.size == 0
    res.each_pair do |problem, status|
      problem.status = status
      problem.save
      puts "Obnovqvane"
    end
  end
  #not working script
  def retrieve_status(not_judged_runs)
    return {}
    @Timus_statuses = {:OK => "Accepted", :Compile => /Compilation error/}
    runs_to_be_judged = not_judged_runs.sort_by{|temp_run| temp_run.realid}
    puts runs_to_be_judged.inspect
    problem_statuses = {}
    timus_status_url = URI.parse('http://acm.timus.ru/status.aspx')
    next_page = '/status.aspx?count=100'
    next_page_extractor = /\<A HREF=\"(.*?)\"\>Next/
    status_extractor =/(\<TABLE class=\"status\".*?\<\/TABLE\>)/
    while !runs_to_be_judged.empty?
        
      res = Net::HTTP.start(timus_status_url.host, timus_status_url.port) {|http|
        http.get(next_page)
      }
      body = res.body
      # puts body
      body =~ next_page_extractor
      next_page =$1[-50, 50]
      next_page = next_page[next_page.index("status"), next_page.length]
      next_page.gsub!("&amp;", "&")
      next_page = "/" + next_page
 
      body =~ status_extractor
      status_string = $1
      status_string.gsub!("<BR>"," ")
        
      status_xml = REXML::Document.new(status_string)
      status_xml.elements[1].each_with_index do |val, idx|
        if idx == 0
          next
        end
        if runs_to_be_judged.empty?
          break
        end
        if val[0][0].to_s == runs_to_be_judged.last().realid.to_s
          if val[6][0].to_s =~ /\d/
            problem_statuses[runs_to_be_judged.last] = val[5][0].to_s
          elsif val[5][0].to_s == @Timus_statuses[:OK]
            problem_statuses[runs_to_be_judged.last] = val[5][0].to_s
          elsif val[5][0].to_s =~ @Timus_statuses[:Compile]
            problem_statuses[runs_to_be_judged.last] = @Timus_statuses[:Compile].source
          end
          runs_to_be_judged.pop
        end
      end
    end
    problem_statuses
  end
  
  private 
  def Uva.calculate_difficulty(submissions, submit_succ, authors, auth_succ)
    accepts = authors.value.to_f * auth_succ.value.to_f
    if accepts < 100
      return 5
    elsif accepts < 275
      return 4
    elsif accepts < 575
      return 3
    elsif accepts < 1000
      return 2
    else
      return 1
    end
  end
    
  def Uva.construct_real_id(description_id, submit_id)
    description_id + "/" + submit_id
  end
  
  def Uva.get_description_id(real_id)
    real_id.split("/")[0]
  end
  
  def Uva.get_submit_id(real_id)
    real_id.split("/")[1]
  end
  
  def Uva.construct_description_url(real_id)
    description_id = get_description_id(real_id)
    "/onlinejudge/external/" + (description_id.to_i / 100).to_s + "/" + description_id + ".html"
  end
end
